# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

from . import _

import etude.plugins as ep
import etude.client as ec
import etude.gui as eg
import common

import gtk

class DefaultPlaylist(ep.PluginPanel):

    _type = ep.E_PANEL_TYPE_PLAYLIST
    _short_name = "Playlist"
    _show_name = _("Playlist")
    _short_descr = ""
    _version = "0.1"
    _unique = "Default_Playlist-0.1" # short name + version is enough, just to identify loaded
    _title = _("Playlist")
    _config = { 'format': '<smart> {\\n[small]<artist> [i](<album>)[/i][/small]}',
            'autoscroll': '1',
            'show_row_numbers': '1',
            'show_playlist_name': '1'}
    __author__ = "Szentandrási István"
    _ui = """
        <ui>
            <popup name="playlist_add_menu">
                <menuitem action="playlist_open_files" />
                <menuitem action="playlist_open_url" />
            </popup>
            <popup name="playlist_remove_menu">
                <menuitem action="playlist_remove_selected" />
                <menuitem action="clear" />
            </popup>
            <popup name="playlist_context_menu">
                <menuitem action="playlist_remove_selected" />
                <menuitem action="clear" />
            </popup>
        </ui>
        """

    def __init__(self, control):

        self._actions = [
                ('playlist_open_files', gtk.STOCK_ADD, _("Add files/folders"), '<Ctrl>o',
                    None, self.filechooser),
                ('playlist_open_url', gtk.STOCK_ADD, _("Add url"), '<Ctrl>u',
                    None, self.urlchooser),
                ('playlist_remove_selected', gtk.STOCK_REMOVE,
                    _("Remove selected"), None, None, self.remove_selected)
                ]

        ep.PluginPanel.__init__(self, control)
        self.client = self.control.client
        self.set_shadow_type(gtk.SHADOW_NONE)
        self.set_size_request(200, 400)

        self.list = eg.CollectionView(self, self.get_config('format'))
        self.list.show_row_numbers = bool(int(
            self.get_config('show_row_numbers')
            ))
        self.client.playlist.current_active(cb = self.active_name)
        self.list.set_headers_visible(False)
        self.list.set_rules_hint(True)
        self.bind(self.client, "e_playback_current_id", self.song_change)
        self.list.connect("row-activated", self.song_activated)
        self.list.get_selection().set_mode( gtk.SELECTION_MULTIPLE )
        self.list.enable_dnd(True, True)
        self.set_songlist_popup_menu()

        self.pl_scrolledw = gtk.ScrolledWindow()
        self.pl_scrolledw.set_policy(gtk.POLICY_AUTOMATIC,
                gtk.POLICY_AUTOMATIC)
        self.pl_scrolledw.set_shadow_type(gtk.SHADOW_IN)
        self.pl_scrolledw.add(self.list)

        self.vbox = gtk.VBox()
        self.add(self.vbox)
        self.playlist_title = gtk.Label()
        self.playlist_title.set_use_markup(True)
        self.vbox.pack_start(self.playlist_title, False, False)
        self.vbox.pack_start(self.pl_scrolledw)

        self.hbox = gtk.HBox()
        self.vbox.pack_start(self.hbox, False, False)

        self.add_button = gtk.Button()
        eg.format_button(self.add_button, stock_image=gtk.STOCK_OPEN,
                relief=gtk.RELIEF_NONE)

        self.add_button.connect('clicked', self.show_add_popup)
        self.hbox.pack_start(self.add_button, False, False)

        self.rem_button = gtk.Button()
        eg.format_button(self.rem_button, stock_image=gtk.STOCK_REMOVE,
                relief=gtk.RELIEF_NONE)
        self.rem_button.connect('clicked', self.show_rem_popup)
        self.hbox.pack_start(self.rem_button, False, False)
        self.hbox.show_all()

        shuff_button = gtk.Button()
        shuff_action = self.control.actions.get_action("shuffle")
        shuff_action.connect_proxy(shuff_button)
        eg.format_button(shuff_button, no_label=True, force_image=True,
                image=gtk.image_new_from_icon_name('media-playlist-shuffle',
                    gtk.ICON_SIZE_BUTTON),
                relief=gtk.RELIEF_NONE)
        shuff_button.props.label = None
        self.hbox.pack_end(shuff_button, False, False)
        self.hbox.show_all()

        rep_st = gtk.image_new_from_icon_name('media-playlist-repeat',
                gtk.ICON_SIZE_BUTTON)
        self.repeat_button = gtk.ToggleButton()
        repeat_action = self.control.actions.get_action("repeat")
        repeat_action.connect_proxy(self.repeat_button)
        eg.format_button(self.repeat_button, relief=gtk.RELIEF_NONE,
                image=rep_st, force_image=True)
        self.repeat_changed(self.client, self.client.playlist.get_repeat())
        self.bind( self.client, "e_playlist_repeat_changed",
                self.repeat_changed)
        self.bind( self.client, "e_playlist_loaded", self.set_current_name)
        self.hbox.pack_end(self.repeat_button, False, False)

        self.hbox.show_all()
        self.list.show()
        self.pl_scrolledw.show()
        if self.get_config('show_playlist_name') == '1':
            self.playlist_title.show()
        self.vbox.show()
        self.show()
        self.list.connect('key_press_event', self.on_list_button_press)
        self.list.connect('collection_loaded', self.on_collection_loaded)

    def set_songlist_popup_menu(self):
        menu = self.control.uimanager.get_widget("/playlist_context_menu")
        self.list.set_menu(None, menu)

    def on_collection_loaded(self, songlist, name, coll_class):
        self.playlist_title.set_markup("<big><b>"+name+"</b></big>")
        return False

    def __menu_position_setter(self, menu, widget):
        """ for popup menus, which appear after clicking on a button"""
        x, y = widget.get_toplevel().get_position()
        alloc = widget.get_allocation()
        x += alloc.x + int(alloc.width/2)
        y += alloc.y + int(alloc.height)
        return (x, y, True)


    def on_list_button_press(self, widget, event, data = None):
        """ enable delete button support for deleting songs from playlist """
        if event.keyval == gtk.keysyms.Delete:
            self.remove_selected(widget)
        return False

    def active_name(self, name):
        """set the active playlist's name """
        self.list.set_coll_name(name, "Playlists")

    def repeat_changed(self, widget, value):
        """the song repeat configuration values changed"""
        ac = self.control.actions.get_action("repeat")
        ac.set_sensitive(False)
        if value == ec.PLAYLIST_REPEAT_ONE:
            self.repeat_button.set_active(True)
            self.repeat_button.set_label("1")
        elif value == ec.PLAYLIST_REPEAT_ALL:
            self.repeat_button.set_active(True)
            self.repeat_button.set_label("*")
        else:
            self.repeat_button.set_active(False)
            #self.repeat_button.set_label("")
            self.repeat_button.props.label = None
        ac.set_sensitive(True)
        return False


    def song_change(self, widget, song_id):
        """the current song changed, scroll to the song, if possible"""
        ind = self.list.playlist_position
        if ind <= 0 :
            return False
        if self.get_config('autoscroll') == '1':
            self.list.scroll_to_cell((ind,),
                    use_align = True,
                    row_align = 0.5)
        return False

    def song_activated(self, widget, path, column):
        """a song was double clicked"""
        self.client.playlist.set_next(path[0], play = True)

    def show_add_popup(self, widget, data=None):
        """show the popup for adding urls/files to the playlist"""

        menu = self.control.uimanager.get_widget("/playlist_add_menu")
        menu.popup(None, None, self.__menu_position_setter, 1, 0, widget)

    def show_rem_popup(self, widget, data=None):
        """show popup for removing songs/clearing the playlist"""

        menu = self.control.uimanager.get_widget("/playlist_remove_menu")
        menu.popup(None, None, self.__menu_position_setter, 1, 0, widget)

    def filechooser(self, widget, data = None):
        """show a file chooser... remote or else"""
        paths = common.filechooser(self.get_toplevel(), self.control)
        for isdir, path in paths:
            if isdir:
                self.client.playlist.radd(path)
            else:
                self.client.playlist.add_url(path)
        return False

    def urlchooser(self, widget, data = None):
        """show the url chooser"""
        entry_text = common.url_chooser_dialog(self.get_toplevel())
        if entry_text:
            self.client.playlist.add_url(entry_text)
        return False

    def remove_selected(self, widget, data = None):
        """remove selected songs from the playlist"""
        sel = self.list.get_selection()
        rows = [a[0] for a in sel.get_selected_rows()[1]]
        rows.sort() #just in case
        for i in xrange(len(rows)):
            self.client.playlist.remove_entry(rows[i]-i)
        return False

    def set_current_name(self, client, name):
        """callback for current active name"""
        self.list.set_coll_name(name, "Playlists")

    def show_preferences(self, parent):
        dialog = gtk.MessageDialog( parent,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                gtk.MESSAGE_OTHER,
                buttons=gtk.BUTTONS_OK_CANCEL
                )
        dialog.set_default_size(300, 200)
        dialog.set_title(_("Playlist settings"))
        #inputfield
        entry = gtk.Entry()
        entry.set_text(self.get_config('format'))
        #allow using enter
        entry.connect('activate',
                lambda widget: dialog.response(gtk.RESPONSE_OK))
        entry.set_tooltip_text(_("""
to group properties use {} - the contents are only shown if all the
properties inside are set

| is a column separator
<artist> - artist
<album> - album
<smart> - title or channel or filename in this order
<title> - title
<channel> - radio channel
<tracknr> - tracknumber
<url> - path - if file
<bitrate>- bitrate
<filename>- filename - if file
<duration> - song length
<date> - date
<genre> - genre
<comment> - comment"""))
        table = gtk.Table(rows = 4, columns = 2)
        table.attach(gtk.Label(_("Format")+":"), 0, 1, 0, 1,
                xoptions = 0, yoptions = 0)
        table.attach(entry, 1, 2, 0, 1,
                xoptions = gtk.FILL|gtk.EXPAND, yoptions = 0)
        tbutton = gtk.CheckButton(_("Autoscroll to current"))
        tbutton.set_active(self.get_config('autoscroll') == '1')
        table.attach(tbutton, 1, 2, 1, 2,
                xoptions = gtk.FILL|gtk.EXPAND, yoptions = 0)

        num_button = gtk.CheckButton(_("Show playlist positions"))
        num_button.set_active(self.get_config('show_row_numbers') == '1')
        table.attach(num_button, 1, 2, 2, 3,
                xoptions = gtk.FILL|gtk.EXPAND, yoptions = 0)

        name_button = gtk.CheckButton(_("Show playlist name"))
        name_button.set_active(self.get_config('show_playlist_name') == '1')
        table.attach(name_button, 1, 2, 3, 4,
                xoptions = gtk.FILL|gtk.EXPAND, yoptions = 0)

        dialog.vbox.add(table)
        dialog.show_all()
        res = dialog.run()
        if res == gtk.RESPONSE_OK:
            view_format = entry.get_text()
            scroll = str(int(tbutton.get_active()))
            show_num = str(int(num_button.get_active()))
            show_name = str(int(name_button.get_active()))
            self.set_config('format', view_format)
            self.set_config('autoscroll', scroll)
            self.set_config('show_row_numbers', show_num)
            self.set_config('show_playlist_name', show_name)
            self.list.show_row_numbers = num_button.get_active()
            self.list.set_format(view_format)
            self.playlist_title.set_property('visible',
                    name_button.get_active())
        dialog.destroy()



